package com.tanhan.mindapp.config.inter;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Collection;

@Component("ss")
public class SecurityService {

    /**
     * 验证用户是否拥有指定权限
     * @param permission 权限字符串
     * @return 拥有权限返回true，否则返回false
     */
    public boolean hasPermi(String permission) {
        if (ObjectUtils.isEmpty(permission)) {
            return false;
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication);
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        return authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(auth -> auth.equals(permission));
    }
}
